package com.it.day3;

import java.util.concurrent.TimeUnit;

/**
 * ClassName: InterrputDemo
 * Description: 线程中断机制
 *
 * @Author: csx
 * @Create: 2025/5/9 - 23:57
 * @version: v1.0
 */
public class InterruptDemo {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName() + " 的中断标识位为：" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + " 的中断标识位为：" + Thread.interrupted());
        System.out.println("---------------------");
        Thread.currentThread().interrupt();
        System.out.println("---------------------");
        System.out.println(Thread.currentThread().getName() + " 的中断标识位为：" + Thread.interrupted());
        System.out.println(Thread.currentThread().getName() + " 的中断标识位为：" + Thread.interrupted());
    }

    /**
     * 中断异常演示
     */
    private static void m2() {
        Thread t1 = new Thread(() -> {
            while (true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("-----------" + Thread.currentThread().getName() + "我被中断了");
                    break;
                }

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    e.printStackTrace();
                }

                System.out.println(Thread.currentThread().getName() + " 正在运行！");
            }
        }, "t1");
        t1.start();

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            t1.interrupt();
        }, "t2").start();
    }

    /**
     * 中断演示
     */
    private static void m1() {
        Thread t1 = new Thread(() -> {
            while (true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("-----------" + Thread.currentThread().getName() + "我被中断了");
                    break;
                }
                System.out.println(Thread.currentThread().getName() + " 正在运行！");
            }
        }, "t1");
        t1.start();

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            t1.interrupt();
        }, "t2").start();
    }
}

























